package com.gec.service;

import com.gec.dao.DeptMapper;
import com.gec.dao.LeaveMapper;
import com.gec.dao.ProcessConfigMapper;
import com.gec.domain.Leave;
import com.gec.domain.PageBean;
import com.gec.domain.ProcessConfig;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Aniki
 * @date  2021-12-2
 */
@Service
public class LeaveServiceImpl extends BaseService implements LeaveService {

    /**自动装配两个mapper*/
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private LeaveMapper leaveMapper;
    @Autowired
    private ProcessConfigMapper processConfigMapper;

    /**自动装配(工作流相关的service)*/
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RuntimeService runtimeService;


    @Override
    public String getDeptLeader(String deptId) {

        return deptMapper.findDeptLeaderId(deptId);
    }

    @Override
    public String getHigherDeptLeader(String deptId) {
        /**获取上级部门的Id*/
        String highDept = deptMapper.findHigherLeverDept(deptId);
        /**根据此Id 得到这个部门的领导*/
        return  deptMapper.findDeptLeaderId(highDept);
    }

    @Override
    public void updateAssigneeAndTask(String insId, String taskId, String assignee) {

        int count = leaveMapper.updateAssigneeAndTask(insId, taskId, assignee);
    }

    /**A.发起申请业务*/
    private Map<String,Object> setVariables(Leave leave){
        Map<String, Object> vars = new HashMap<>();
        //发起人
        vars.put("inputUser",leave.getInitiator());
        //开始日期
        vars.put("startDate",dateToStr(leave.getStartDate()));
        //结束日期
        vars.put("endDate",dateToStr(leave.getEndDate()));
        //请假原因
        vars.put("reason",leave.getReason());
        //请假天数
        vars.put("days",leave.getDays());
        //请假类型
        vars.put("leaveType",leave.getLeaveType());
        //取消任务
        vars.put("cancel","false");
        return vars;
    }
     /**提交申请*/
     private void commitLeave(String initiator,String insID){
         //查询任务
         Task task = taskService.createTaskQuery()
                 .taskAssignee(initiator)
                 .processInstanceId(insID)
                 .singleResult();

         taskService.complete(task.getId());
     }
    /**开启流程与*/
    @Override
    public void startProcess(Leave leave) throws SQLException {
        /**计算天数*/
       int days =  calDays(leave.getStartDate(), leave.getEndDate());
        //设置天数
       leave.setDays(days);
        //包装流程变量
        Map<String, Object> proVars = setVariables(leave);
        //查询系统的流程字典表  - 流程定义ID
        ProcessConfig config = processConfigMapper.getProcConfigByCategory("请假流程");
        String procDefId = config.getProcDefId();
        //开启流程实例
        ProcessInstance instance = runtimeService.startProcessInstanceById(procDefId,proVars);
        /**补全leave信息  流程定义ID，流程实例ID，创建时间，status*/
        leave.setProcDefId(procDefId);
        leave.setProcInstId(instance.getId());
        leave.setCreateTime(dateToStr(new Date()));
        leave.setStatus("办理中");

        //保存到t_leave表
        leaveMapper.addLeave(leave);
        commitLeave(leave.getInitiator(),instance.getId());
    }


    /**B.查询我发起的业务*/
    @Override
    public PageBean<Leave> queryMyInitiate(String initiator) {
        //暂时省略分页功能
        /**获取列表*/
        List<Leave> list = leaveMapper.queryMyInitiate(initiator);
        PageBean pageBean = new PageBean();
       /**临时设置*/
        pageBean.setCount(list.size());
        pageBean.setList(list);
        return pageBean;
    }

    /**C.查询待我审批业务*/
    @Override
    public PageBean<Leave> queryWaitMyApprove(String assigneeId, int page, int limit) {
       /* 暂不设置分页*/
        /**查询审批的任务清单*/
        List<Leave> list = null;
        PageBean pageBean = new PageBean();
        list = leaveMapper.queryWaitMyApprove(assigneeId);
        /**封装数据到分页Bean*/
        pageBean.setCount(list.size());
        pageBean.setList(list);
        return pageBean;
    }
   /**查询待我审批的任务详情*/
    @Override
    public Leave queryMyTaskByTaskId(String taskId) {

        return leaveMapper.queryMyTaskByTaskId(taskId);
    }


    /**D.查询我已审批业务*/

    @Override
    public void updateStatusByInstance(String insID,String status) {

        int count = leaveMapper.updateStatus(insID,status);
        /*暂不处理更新失败*/
    }

    @Override
    public void completeMyApprove(Map data) {

        String deptId = (String) data.get("deptId");
        String taskId = (String) data.get("taskId");
        String appFlag = (String) data.get("appFlag");
        /**获取更高一级部门ID*/
        String pDeptId = deptMapper.findHigherLeverDept(deptId);
        if ("top".equals(pDeptId)) {
              //老板  处理意见
            data.put("bossApp",appFlag);
        } else {
             //主管  处理意见
            data.put("deptApp",appFlag);
        }
         /**把办理人设置为空*/
        leaveMapper.updateAssigneeByTask(taskId,null);
        taskService.complete(taskId,data);
    }



}
